package com.FH.applyFrom.assist_sth;

import com.FH.organization.department.DepartmentResource;
import com.FH.organization.operator_log.OperatorLogPullDTO;
import com.FH.organization.operator_log.OperatorLogResource;
import com.FH.organization.people.KamMemberResource;
import com.FH.organization.siperintend_item.SiperintendItemPullDTO;
import com.FH.organization.siperintend_item.SiperintenditemResourse;
import com.FH.organization.suggestion.SuggestionResource;
import com.FH.organization.work_flow.WorkFlowPullDTO;
import com.FH.organization.work_flow.WorkFlowResource;
import com.FH.util.AccessDB;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/12/13.
 */
@Stateless
public class AssistSthImpl extends AccessDB implements AssistSthDAO {
    @Inject
    KamMemberResource kamMemberResource;
    @Inject
    DepartmentResource departmentResource;
    @Inject
    SiperintenditemResourse siperintenditemResourse;
    @Inject
    OperatorLogResource operatorLogResource;
    @Inject
    WorkFlowResource workFlowResource;
    @Inject
    SuggestionResource suggestionResource;

    @Override
    public ResultDTO getSiperintendInfo(String search, String page, String size) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            String sqlexit = "select count(1) from assist_sth where 1=1 ";

            String sql_w = "";//查询条件sql组合

            String sql_page = "";//分页sql组合
            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok) + "," + size + "";
            }

            if (json.has("siperintend_id")) {
                sql_w += " AND siperintend_id ='" + json.getString("siperintend_id") + "'";
            }

            if (json.has("isverify")) {
                sql_w += " AND isverify ='" + json.getString("isverify") + "'";
            }
//            else {
//                sql_w += " AND (isverify IS NULL OR isverify=0)";
//            }

            String sql_ok = sqlexit + sql_w;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<AssistSthShowDTO> result = new ArrayList<AssistSthShowDTO>();
            if (!existName.equals("0")) {
                String sql = "select siperintend_id,siperintend_desc,siperintend_type,member_id,result,title,assist_men,assist_org,isverify from assist_sth where 1=1 " + sql_w + " ORDER BY create_time DESC" + sql_page;
                seresult = this.getReportingTo(sql);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++) {

                    AssistSthShowDTO siperintendShowDTO = new AssistSthShowDTO();
                    siperintendShowDTO.setSiperintend_id(seresult.get(i)[1]);
                    siperintendShowDTO.setSiperintend_desc(seresult.get(i)[2]);
                    siperintendShowDTO.setSiperintend_type(seresult.get(i)[3]);
                    siperintendShowDTO.setMember_id(seresult.get(i)[4]);
                    siperintendShowDTO.setResult(seresult.get(i)[5]);
                    siperintendShowDTO.setTitle(seresult.get(i)[6]);
                    siperintendShowDTO.setAssist_men(seresult.get(i)[7]);
                    siperintendShowDTO.setAssist_org(seresult.get(i)[8]);
                    siperintendShowDTO.setIsverify(seresult.get(i)[9]);
                    ResultDTO siperintendItems = null, sp_member = null, assist_men = null, assist_org = null, suggestion = null;
                    siperintendItems = siperintenditemResourse.getSiperintendItemInfo("{siperintend_id:" + seresult.get(i)[1] + "}", "1", "1000");
                    siperintendShowDTO.setSiperintendItemShowDTOs(siperintendItems.getValues());
                    sp_member = kamMemberResource.getUserListInfo("{member_id:" + seresult.get(i)[4] + "}", "1", "1");
                    siperintendShowDTO.setSp_memberlist(sp_member.getValues());
                    assist_men = kamMemberResource.getUserListInfo("{member_id:" + seresult.get(i)[7] + "}", "1", "1");
                    siperintendShowDTO.setAssist_menlist(assist_men.getValues());
                    assist_org = departmentResource.getDepartmentInfo("{organization_id:" + seresult.get(i)[8] + "}", "1", "1");
                    siperintendShowDTO.setAssist_orglist(assist_org.getValues());
                    if (seresult.get(i)[1] != null && !seresult.get(i)[1].equals("")) {

                        suggestion = suggestionResource.getSuggestionInfo("{form_id:" + seresult.get(i)[1] + "}", "1", "100");
                        siperintendShowDTO.setSuggestionShowDTOs(suggestion.getValues());
                    }
                    result.add(siperintendShowDTO);
                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setStr(result.size() + "");
            resultDTO.setValues(result);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultDTO;
    }

    @Override
    public ResultDTO addSiperintendInfo(AssistSthPullDTO assistSthPullDTO) {
        String sql_isHas = "select count(1) from assist_sth WHERE siperintend_id='" + assistSthPullDTO.getSiperintend_id() + "'";

        String existName = getReportingToOne(sql_isHas);//插入前，查询是否有重复字段

        if (!existName.equals("0")) {
            return updateSiperintendInfo(assistSthPullDTO);
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式化

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        int resultls = 0;

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();

        if (existName.equals("0")) {

            String sql = "";

            //构建插入sql
            sql += "INSERT  INTO assist_sth(siperintend_id,title,siperintend_desc,siperintend_type,member_id,result,create_time,assist_men,assist_org,isverify) " +
                    "VALUES('" + uuid + "','" + assistSthPullDTO.getTitle() + "','" + assistSthPullDTO.getSiperintend_desc() + "','" + assistSthPullDTO.getSiperintend_type() + "','" + assistSthPullDTO.getMember_id() + "','"
                    + assistSthPullDTO.getResult() + "','" + df.format(new Date()) + "','" + assistSthPullDTO.getAssist_men() + "','" + assistSthPullDTO.getAssist_org() + "','0')";
            //插入业务表
            resultls = addReportingTo(sql);

        }
        if (resultls != 0) {
            /**
             * JSON解析集合、参会人
             */
            if (null != assistSthPullDTO.getJsonitems() && !"".equals(assistSthPullDTO.getJsonitems())) {
                String Jsonitems = assistSthPullDTO.getJsonitems();
                try {
                    JSONArray array = new JSONArray(Jsonitems);
                    if (array != null && array.length() > 0) {
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject jsonObject = array.getJSONObject(i);
                            String itemid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                            String work_task = jsonObject.getString("work_task");
                            String progress_situation = jsonObject.getString("progress_situation");
                            String plan_finish_time = jsonObject.getString("plan_finish_time");
                            String duty_leader = jsonObject.getString("duty_leader");
                            String duty_organization = jsonObject.getString("duty_organization");
                            String duty_men = jsonObject.getString("duty_men");
                            SiperintendItemPullDTO siperintendItemPullDTO = new SiperintendItemPullDTO();
                            siperintendItemPullDTO.setWork_task(work_task);
                            siperintendItemPullDTO.setProgress_situation(progress_situation);
                            siperintendItemPullDTO.setPlan_finish_time(plan_finish_time);
                            siperintendItemPullDTO.setDuty_leader(duty_leader);
                            siperintendItemPullDTO.setDuty_organization(duty_organization);
                            siperintendItemPullDTO.setDuty_men(duty_men);
                            siperintendItemPullDTO.setSiperintend_id(uuid);
                            siperintenditemResourse.addSiperintendItemInfo(siperintendItemPullDTO);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            //日志操作
            OperatorLogPullDTO operatorlogPullDTO = new OperatorLogPullDTO();
            operatorlogPullDTO.setWork_form_id(uuid);
            operatorlogPullDTO.setOperator_log_type("协办事宜");
            operatorlogPullDTO.setOperator_log_title(assistSthPullDTO.getTitle());
            operatorlogPullDTO.setOperator_log_content(assistSthPullDTO.getSiperintend_desc());
            operatorlogPullDTO.setMember_id(assistSthPullDTO.getMember_id());
            operatorLogResource.addOperatorLogInfo(operatorlogPullDTO);
            //流程上报

            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(uuid);
            workFlowPullDTO.setWork_flow_type("assist_sth");
            workFlowPullDTO.setWork_flow_desc("协办事宜请求审批");
            workFlowPullDTO.setWork_flow_date(df.format(new Date()));
            workFlowPullDTO.setWork_flow_order("0");
            workFlowPullDTO.setWork_flow_createid(assistSthPullDTO.getMember_id());
            workFlowPullDTO.setWork_flow_approval(assistSthPullDTO.getReport_people());
            workFlowPullDTO.setWork_flow_approval_organization_id(assistSthPullDTO.getWork_flow_approval_organization_id());
//            workFlowPullDTO.setFlow_path_id(assistSthPullDTO.getFlow_path_id());
            workFlowPullDTO.setWork_flow_suggestion("");
            workFlowResource.addWorkFlowInfo(workFlowPullDTO);

            resultDTO.setStr(uuid);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }

        return resultDTO;
    }

    @Override
    public ResultDTO updateSiperintendInfo(AssistSthPullDTO assistSthPullDTO) {
        ResultDTO resultDTO = new ResultDTO();
        if (null != assistSthPullDTO.getJsonitems() && !"".equals(assistSthPullDTO.getJsonitems())) {
            String Jsonitems = assistSthPullDTO.getJsonitems();
            try {
                JSONArray array = new JSONArray(Jsonitems);
                if (array != null && array.length() > 0) {
                    SiperintendItemPullDTO siperintendItemPullDTOdelete = new SiperintendItemPullDTO();
                    siperintendItemPullDTOdelete.setSiperintend_id(assistSthPullDTO.getSiperintend_id());
                    siperintenditemResourse.deleteSiperintendItemInfo(siperintendItemPullDTOdelete);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        String itemid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                        String work_task = jsonObject.getString("work_task");
                        String progress_situation = jsonObject.getString("progress_situation");
                        String plan_finish_time = jsonObject.getString("plan_finish_time");
                        String duty_leader = jsonObject.getString("duty_leader");
                        String duty_organization = jsonObject.getString("duty_organization");
                        String duty_men = jsonObject.getString("duty_men");
                        SiperintendItemPullDTO siperintendItemPullDTO = new SiperintendItemPullDTO();
                        siperintendItemPullDTO.setWork_task(work_task);
                        siperintendItemPullDTO.setProgress_situation(progress_situation);
                        siperintendItemPullDTO.setPlan_finish_time(plan_finish_time);
                        siperintendItemPullDTO.setDuty_leader(duty_leader);
                        siperintendItemPullDTO.setDuty_organization(duty_organization);
                        siperintendItemPullDTO.setDuty_men(duty_men);
                        siperintendItemPullDTO.setSiperintend_id(assistSthPullDTO.getSiperintend_id());
                        siperintenditemResourse.addSiperintendItemInfo(siperintendItemPullDTO);
                    }
                }


                String QUERY = "";

                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = df.format(new Date());
                //更新sql语句
                QUERY += "update assist_sth set create_time ='" + time + "'";

                if (null != assistSthPullDTO.getTitle() && !"".equals(assistSthPullDTO.getTitle())) {
                    QUERY += " title = '" + assistSthPullDTO.getTitle() + "'";
                }
                if (null != assistSthPullDTO.getAssist_men() && !"".equals(assistSthPullDTO.getAssist_men())) {
                    QUERY += " assist_men = '" + assistSthPullDTO.getAssist_men() + "'";
                }
                if (null != assistSthPullDTO.getAssist_org() && !"".equals(assistSthPullDTO.getAssist_org())) {
                    QUERY += " assist_org = '" + assistSthPullDTO.getAssist_org() + "'";
                }
                QUERY += " where siperintend_id = '" + assistSthPullDTO.getSiperintend_id() + "'";
                int result = this.addReportingTo(QUERY);

                // 判断SQl是否执行成功
                if (result != 0) {
                    resultDTO.setStr(assistSthPullDTO.getSiperintend_id());
                    resultDTO.setStatus("90000");//
                    resultDTO.setDescritpion(warnSrc.update_success);
                } else {
                    resultDTO.setStatus("90001");//
                    resultDTO.setDescritpion(warnSrc.update_fail);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return resultDTO;
    }

    @Override
    public ResultDTO deleteSiperintendInfo(AssistSthPullDTO assistSthPullDTO) {
        //删除之前查询一下该表是否有记录
        String sql = "select count(1) from assist_sth  where siperintend_id='" + assistSthPullDTO.getSiperintend_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        if (!existName.equals(0)) {
            String QUERY = "";
            QUERY += "delete from assist_sth where siperintend_id='" + assistSthPullDTO.getSiperintend_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        ResultDTO resultDTO = new ResultDTO();
        if (result != 0) {
            SiperintendItemPullDTO siperintendItemPullDTO = new SiperintendItemPullDTO();
            siperintendItemPullDTO.setSiperintend_id(assistSthPullDTO.getSiperintend_id());
            siperintenditemResourse.deleteSiperintendItemInfo(siperintendItemPullDTO);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }
}
